#include <stdio.h>
#include <stdlib.h>

struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2);

struct ListNode {
    int val;
    struct ListNode *next;
};

int main() {
    struct ListNode n1, n2, n3, *head, *p;
    n1.val = 2;
    n2.val = 4;
    n3.val = 3;
    head = &n1;
    n1.next = &n2;
    n2.next = &n3;
    n3.next = NULL;
    p = head;
    struct ListNode a1, a2, a3, *aHead, *ap;
    a1.val = 5;
    a2.val = 6;
    a3.val = 4;
    aHead = &a1;
    a1.next = &a2;
    a2.next = &a3;
    a3.next = NULL;
    ap = aHead;
    struct ListNode *pNode = addTwoNumbers(p, ap);
    while (pNode != NULL) {
        printf("%d", pNode->val);
        pNode = pNode->next;
    }
}

struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) {
    struct ListNode *i = l1,  //把l1的首地址赋值给i
            *j = l2,          //同上
            *p = (struct ListNode *) malloc(sizeof(struct ListNode)); //用malloc动态开辟结构 ListNode空间给指针p
    p->next = NULL;
    struct ListNode *result = p;  //把p的地址赋值给指针result
    int a,
        b,
        sum,
        carry = 0;  //记录进位数
    while (i || j) {
        a = i ? i->val : 0;  //如果i不为null a = i->val,否则为0
        b = j ? j->val : 0;  //同上
        sum = a + b + carry;
        carry = sum / 10;
        p->next = (struct ListNode *) malloc(sizeof(struct ListNode)); //为指针p的下一个节点开辟结构体空间
        p = p->next;    //把p的下一个节点 赋值给当前p
        p->next = NULL;  //把当前p的下一个节点赋值NULL 也就是上一个的p->next->next = NULL
        p->val = sum % 10; //取余
        if (i)
            i = i->next;
        if (j)
            j = j->next;
    }
    if (carry) {
        p->next = (struct ListNode *) malloc(sizeof(struct ListNode));
        p = p->next;
        p->val = 1;
        p->next = NULL;
    }
    return result->next;
}